package com.gitee.wsl.flow

import com.gitee.wsl.ext.ApplicationConfig
import kotlinx.atomicfu.atomic
import kotlinx.coroutines.ExperimentalForInheritanceCoroutinesApi
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.FlowCollector
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.onEach
import timber.log.Timber

fun <T> Flow<T>.debugLog(subject: String): Flow<T> =
    if (ApplicationConfig.isDebug) {
        onEach { Timber.i( ">>> $subject: $it") }
    } else {
        this
    }

 @OptIn(ExperimentalForInheritanceCoroutinesApi::class)
 fun <T> SharedFlow<T>.debugLog(subject: String): SharedFlow<T> =
    if (ApplicationConfig.isDebug) {
        val self = this

        object : SharedFlow<T> by self {
            val subscriberCount = atomic(0)

            override suspend fun collect(collector: FlowCollector<T>): Nothing {
                val count = subscriberCount.getAndIncrement()

                self.collect {
                    Timber.i(">>> $subject ~ $count: $it")
                    collector.emit(it)
                }
            }
        }
    } else {
        this
    }